
package cn.zebra.dev.ibatis.plus.utils;

import cn.zebra.dev.common.constant.ParamsConstant;
import cn.zebra.dev.common.filter.SqlFilter;
import cn.zebra.dev.common.utils.StrUtils;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 查询参数
 *
 * @author Mark runnable@sina.cn
 * @since 2.0.0 2017-03-14
 */
public class Query<T> extends LinkedHashMap<String, Object> {

    private static final long serialVersionUID = 1L;
    /**
     * mybatis-plus分页参数
     */
    private Page<T> page;
    /**
     * 当前页码
     */
    private int currPage = 1;
    /**
     * 每页条数
     */
    private int limit = 10;

    public Query(Integer page, Integer limit) {
        this.currPage = page;
        this.limit = limit;
        this.put("offset", (currPage - 1) * limit);
        this.put(ParamsConstant.PAGE, currPage);
        this.put(ParamsConstant.LIMIT, limit);
        this.page = new Page<>(currPage, limit);
    }

    public Query(Map<String, Object> params) {
        this.putAll(params);

        //分页参数
        if (params.containsKey(ParamsConstant.PAGE)) {
            currPage = Integer.parseInt(params.get(ParamsConstant.PAGE).toString());
        }
        if (params.containsKey(ParamsConstant.LIMIT)) {
            limit = Integer.parseInt(params.get(ParamsConstant.LIMIT).toString());
        }

        this.put("offset", (currPage - 1) * limit);
        this.put(ParamsConstant.PAGE, currPage);
        this.put(ParamsConstant.LIMIT, limit);

        //防止SQL注入（因为sidx、order是通过拼接SQL实现排序的，会有SQL注入风险）
        String field = SqlFilter.sqlInject((String) params.get("sidx"));
        String order = SqlFilter.sqlInject((String) params.get("order"));
        this.put("field", field);
        this.put("order", order);

        //mybatis-plus分页
        this.page = new Page<>(currPage, limit);

        //排序
        if (StrUtils.isNotBlank(field) && StrUtils.isNotBlank(order)) {
            ArrayList<OrderItem> orders = new ArrayList<>();
            OrderItem item = new OrderItem();
            item.setColumn(field);
            item.setAsc("ASC".equalsIgnoreCase(order));
            orders.add(item);
            this.page.setOrders(orders);
        }

    }

    public Page<T> getPage() {
        return page;
    }

    public int getCurrPage() {
        return currPage;
    }

    public int getLimit() {
        return limit;
    }
}
